package br.com.netomarin.bundesliga.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.netomarin.bundesliga.model.MatchModel;
import br.com.netomarin.bundesliga.model.PlayerModel;
import br.com.netomarin.bundesliga.persistence.Match;

public class ConfirmMatchServlet extends HttpServlet {

	private static final long serialVersionUID = -8468594332671758394L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		PrintWriter writer = resp.getWriter();
		String matchKey = req.getParameter("match");
		
		Match m = MatchModel.loadMatchByKey(matchKey);

		if (m.isConfirmed()) {
			writer.print("partida confirmada anteriormente");
		} else if (m.isEscalated()) {
			writer.print("partida já escalada e enviada para os moderadores. Aguarde a decisão oficial.");
		}else {
			if (m.getChallengedMatch() != null && !m.getChallengedMatch().isEmpty()) {
				MatchModel.deleteMatch(m.getChallengedMatch());
			}

			MatchModel.confirmMatch(m);
			PlayerModel.processPlayersMatch(m);
			writer.print("partida confirmada com sucesso");
		}
	}
}